<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    //用户登录
    public function check(Request $request)
    {
        // 参数校验
        $rule = [
            'username' => 'required',
            'password' => 'required|min:6',
            'captcha' => 'required|captcha'
        ];
        $message = [
            'username.required' => '用户名不能为空',
            'password.required' => '密码不能为空',
            'password.min' => '密码最少为6位',
            'captcha.required' => '验证码不能为空',
            'captcha.captcha' => '验证码有误'
        ];
        $validator = Validator::make($request->all(), $rule, $message);

        // 参数验证有误，直接返回
        // if ($validator->fails()) {
        //     foreach ($validator->getMessageBag()->toArray() as $v) {
        //         $msg = $v[0];
        //     }
        //     return response()->json(['code' => 0, 'msg' => $msg]);
        // }

        // 数据库用户密码校验
        $username = $request->post('username');
        $password = $request->post('password');
        $admin = Admin::where('username',$username)->first();
        if($admin->password == md5(md5($password).$admin->salt)){
            // 记录session
            session(['user'=>['id'=>$admin->id,'name'=>$admin->username]]);
            return response()->json(['code' => 1, 'msg' => '登录成功']);
        }else{
            return response()->json(['code' => 0, 'msg' => '用户名或密码错误']);
        }
        
    }

    public function logout(){
        if(session()->has('user')){
            session()->forget('user');
        }
        return redirect('admin/login');
    }
}
